package com.kfm.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Test02 {
    public static void main(String[] args) {

        // 1.注册驱动
        try {
            // 不推荐
            // DriverManager.registerDriver(new Driver());
            Class.forName("com.mysql.cj.jdbc.Driver");

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Connection connection = null;
        Statement statement = null;
        // 2.获取数据库连接
        // url: 主协议:子协议://主机地址:端口(3306)/数据库名称
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/store", "root", "");
            // 3.拼写sql
            String sql = "delete from users where id = 9";
            // 4.获取执行sql的对象
            statement = connection.createStatement();
            // 5.执行sql返回结果 insert/update/delete --> executeUpdate()  select-->executeQuery()
            int rows = statement.executeUpdate(sql);
            if (rows > 0) {
                System.out.println("执行成功");
            } else {
                System.out.println("执行失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 6.释放资源
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
